//
//  PullingRefreshControl.swift
//  SinaBlog
//
//  Created by 有何不可 on 16/1/8.
//  Copyright © 2016年 有何不可. All rights reserved.
//

import UIKit

class PullingRefreshControl: UIRefreshControl {
    
    override init() {
        super.init()
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI() {
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self.snp_center)
            make.width.equalTo(160)
            make.height.equalTo(60)
        }
        
        addObserver(self, forKeyPath: "frame", options: [], context: nil)
    }
    
    var isTurn: Bool = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if refreshing && refreshView.loadingImgView.layer.animationForKey("loadingAnimation") == nil {
            
            refreshView.pullingView.hidden = true
            
            refreshView.loadingAnimation()
        }
        
        if object?.frame.origin.y < -50 && !isTurn {
            
            refreshView.pullAnimation()
            
            isTurn = true
            
        }else if object?.frame.origin.y > -50 && isTurn {
            
            refreshView.pullAnimation()
            
            isTurn = false
        }
        
    }
    
    override func endRefreshing() {
        
        super.endRefreshing()
        
        refreshView.pullingView.hidden = false
        
        refreshView.removeAnimation()
        
        
    }
    
    deinit {
        removeObserver(self, forKeyPath: "loadingAnimation")
    }
    
    private lazy var refreshView: PullingRefreshView = {
        
        let view = NSBundle.mainBundle().loadNibNamed("Refresh", owner: nil, options: nil).last as! PullingRefreshView
        
        return view
        
        }()

}
